﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using GameSchool.Models.Repositories;
using GameSchool.Models.ViewModels;
using GameSchool.Models.Interfaces;
using GameSchool.Models;

//Óklárað!
namespace GameSchool.Controllers
{
    public class LectureController : Controller
    {
        //
        // GET: /Lecture/

        public ActionResult Index(int? ID)
        {

            LectureRepository lec = new LectureRepository();

            var getLecture = lec.GetLectureByID(ID);
            return View(getLecture);
        }

        public ActionResult Create(int? ID)
        {
            //Make sure we have the course ID
            if (ID == null)
                throw new ArgumentNullException("Lecture Create - null passed as parameter");

            //Make sure that the user is teaching this course
            var userID = (Guid)Membership.GetUser().ProviderUserKey;
            var db = new GameSchoolDBDataContext();

            var isTeacher = (from u in db.IsInCourses
                             where u.UserID == userID && u.CourseID == ID
                             select u.IsTeacher).SingleOrDefault();

            //If the user isn't a teacher (!= true because it might be null) nor an admin we throw him to his homepage.
            if (isTeacher != true && !(User.IsInRole("Admin")))
                RedirectToAction("Index", "Home");

            var l = new Lecture();
            l.LevelID = ID;

      
            return View(l);           
        }

        [HttpGet]
        public ActionResult Edit(int? id)
        {
            if (id.HasValue)
            {
                LectureRepository rep = new LectureRepository();
                var model = ( from item in rep.GetLectures()
                                     where item.ID == id
                                     select item).SingleOrDefault();
                             

                if (model != null)
                {
                    //If the newsItem is found in our DB we return it to the edit view..
                    return View(model);
                }
            }
            //If the int? parameter is null or the newsItem isn't fount 
            return View("NotFound");
        }

        [HttpPost]
        public ActionResult Create(Lecture newLecture)
        {
            
            LectureRepository rep = new LectureRepository();
            AssignmentRepository repository = new AssignmentRepository();

            newLecture.Author = (Guid)Membership.GetUser().ProviderUserKey;
            newLecture.DatePub = DateTime.Now;
            var db = new GameSchoolDBDataContext();

            newLecture.CourseID = (from levels in db.Levels
                          where levels.ID == newLecture.LevelID
                          select levels.CourseID).SingleOrDefault();

            rep.AddLecture(newLecture);
            rep.Save();

            var newAssignment = new Assignment();

            newAssignment.ResourceID = newLecture.ID;
            newAssignment.AssignmentType = "Lecture";
            newAssignment.CourseID = newLecture.CourseID;
            newAssignment.LevelID = newLecture.LevelID;

            repository.AddAssignment(newAssignment);
            repository.Save();

            //To get the name of the course to pass to redirect
            var courseID = newLecture.CourseID;


            //return RedirectToAction("Index", "Home");

            return RedirectToAction("Index", "Course/Level/" + courseID );
        }

        [HttpGet]
        //Returns a Json string of comments on the lecture passed as parameter.
        public JsonResult GetComments(int? ID)
        {
            if(ID == null)
                    throw new ArgumentNullException("GetComments - null passed as parameter");

           // CommentLikeRepository commentRep = new CommentLikeRepository();
            GameSchoolDBDataContext db = new GameSchoolDBDataContext();
            var userID = (Guid)Membership.GetUser().ProviderUserKey;

            //First we get a list of the comments for this lecture
            var commentList = (from c in db.Comments
                               where c.LectureID == ID
                               orderby c.CommentDate ascending
                               select c);

            //Create a list of the viewmodel we have to use, since we need more info then just the comments.
            List<GetCommentsModel> modelList = new List<GetCommentsModel>();

            //We go through each comment in the list, and move data from it into the model
            foreach (var c in commentList)
            {
                var model = new GetCommentsModel();
                model.ID = c.ID;
                //We need to count the number of likes for this comment
                model.Likes = (from l in db.Likes
                               where l.CommentID == c.ID
                               select l).Count();
                model.CommentDate = c.CommentDate;
                model.CommentText = c.CommentText;

                //The comment stores the users ID, so we need to get his name from the database.
                model.User = (from u in db.UserProfiles
                              where u.UserID == c.UserID
                              select u.Name).SingleOrDefault();
                //And we want to know if the current user has already liked the comment, so we "count" the number of likes he has on the comment..
                //It'll be either 0 or 1, since a user cant like a comment more then once.
                model.alreadyLike = (from l in db.Likes
                                  where l.CommentID == c.ID && l.UserID == userID
                                  select l).Count();

                //And then we add it into our list of GetCommentModels
                modelList.Add(model);
            }
                                                                                                
            //And simply pass it along.                                                                                                                                                                
            return Json(modelList, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        //Void since it gets its post from AJAX.
        public void AddComments(FormCollection formData)
        {
            int? ID = Convert.ToInt32(formData["ID"]);
            string text = formData["CommentText"];

            if (ID == null || ID < 0)
                throw new ArgumentNullException("AddComment - no lecture ID passed");

                if (text.Length == 0)
                    throw new ArgumentNullException("AddComment - no comment text");

                Comment c = new Comment();

                CommentLikeRepository rep = new CommentLikeRepository();
            //Fill out the rest of the comment with the information required.
            c.UserID = (Guid) Membership.GetUser().ProviderUserKey;
            c.CommentDate = DateTime.Now;
            c.CommentText = text;
            //c.CommentLikes = 0;
            c.LectureID = ID;
            
            //Might want to set this as default in the database.
            c.GivesPoints = false;

            rep.AddComment(c);
            rep.Save();
            return;
            
        }

        [HttpGet]
        public ActionResult Display(int? ID)
        {

            LectureRepository lec = new LectureRepository();
            var getLecture = lec.GetLectureByID(ID);
            
            //Fetch the assignment ID for later use by Resource ID and AssignmentType (see Assignment Repo)
            AssignmentRepository rep = new AssignmentRepository();
            var getAssignmentID = rep.GetAssignmentByID(getLecture.ID);

            AssignmentScore ascore = new AssignmentScore();
            PointsRepository point = new PointsRepository();

            //Check if user has already viewed the Lecture. In that case the user gets no points..
            Guid guid = (Guid)Membership.GetUser().ProviderUserKey; //Load current user into guid
            
            //checkIfViewed will get a value of NULL if no data exists
            var checkIfViewed = rep.CheckIfCompletedByID(guid, getAssignmentID.ID);

            //If there is no data on that assignment then it hasn't been viewed so the user gets points
            if (checkIfViewed == null) 
            {
                //Inputs neccessary data into AssignmentScore
                ascore.UserID = (Guid)Membership.GetUser().ProviderUserKey;
                ascore.AssignmentID = getAssignmentID.ID;
                ascore.Points = Convert.ToInt32(getLecture.MaxPoints * 0.5); //ATM. The user gets half of maxpoints just for viewing the lecture
                ascore.Bonuspoints = 0;

                //Submit and save the data
                point.AddPoints(ascore);
                point.Save();
            }

            return View(getLecture);
        }

        public void LikeComment(int? ID)
        {
            //Connecting to the repository
            var rep = new CommentLikeRepository();
            //Keeping track of the user.
            var userID = (Guid)Membership.GetUser().ProviderUserKey;

            //No rep functions exist ATM to increment the comment counter.
            var db = new GameSchoolDBDataContext();

            //Check if we find a previous like for the same comment from this user.
            var likeExists = (from l in db.Likes
                              where l.CommentID == ID
                              where l.UserID == userID
                              select l).SingleOrDefault();

            //If the like exists we just return - this has been checked to work.
            if (likeExists != null)
                return;


            //Next we find the comment that just got liked
            var comment = (from c in db.Comments
                           where c.ID == ID
                           select c).SingleOrDefault();

            var like = new Like();
            //Next we create the like.
            like.UserID = userID;
            like.CommentID = Convert.ToInt32(ID);
            like.DateLiked = DateTime.Now;

            rep.AddLike(like);
            rep.Save();

        }

        //Test functions 


         private ILectureRepository m_rep = null;

        public LectureController()
        {
            m_rep = new LectureRepository();
        }

        public LectureController(ILectureRepository rep)
        {
            m_rep = rep;
        }

        public ActionResult TestIndex()
        {
            var model = (from items in m_rep.GetLectures()
                         orderby items.DatePub descending
                         select items).Take(10);
            
            return View(model);
        }
    }


}